/**
 * Created by chenxq on 2018/1/5.
 */
import {CallApi} from '../services/api';
export default {
  namespace: 'call',
  state: {
    status:0,  //  0 等待中  1 拨电话  2 通话中  3  结束
    type:'' // 应答类别
  },
  effects: {
    *fetchMakeCall({payload},{call,put}){
      yield put({
        type: 'changeStatus',
        payload: 1,
      });
      const jsonData= yield call(CallApi.makeCall,payload);
      let data=jsonData.data ;
      if(!jsonData.result || !data) {
        yield put({
          type: 'changeStatus',
          payload: 3
        });
      }
      return jsonData;
    },
    *hangUpCall({payload},{call,put}){
      yield put({
        type:'changeStatus',
        payload:3
      })
      const jsonData=yield call(CallApi.hangupCall,payload);
      return jsonData;

    },
    *queryCallStatus({payload},{call,put}){
      let jsonData=yield call(CallApi.queryCallStatus,payload);
      if(jsonData.result){
        let data=jsonData.data || {};
        let {action=''}= data;  //ALERT //分机响铃 ， ANSWERED  分机应答，RING， 被叫响铃 ANSWER 被叫应答，BYE 挂断
        if(action==='BYE'){
          yield put ({
            type:'changeStatus',
            payload:3
          })
        }
        if(action=='ANSWERED' || action=='ANSWER'){
          yield put({
            type:'changeStatus',
            payload:2
          })
          yield put({
            type:'changeCallType',
            payload:action
          })
        }
      }
      return jsonData;
    }
  },

  reducers: {
    changeStatus(state,{payload}){
      return {
        ...state,
        status:payload
      }
    },
    changeCallType(state,{payload}){
      return {
        ...state,
        type:payload
      }
    }

  }
}
